import { useUserInfo } from '@/stores/userInfo';
import { shopuserInfo } from '@/common/api/hbMarket';
import mitt from '@/utils/mitt';
import { ref, onBeforeUnmount } from 'vue';

/**
 * 首页挂载userInfo
 * 1、尝试使用url参数登录
 * 2、获取用户信息
 * 3、EventBus挂载获取用户信息方法
 */
export function useMountUserInfo() {
  const userInfo = useUserInfo();
  // 使用url参数登录
  userInfo.urlLogin();

  const userLoading = ref(false);
  const getUserInfo = async () => {
    if (userLoading.value) return;
    userLoading.value = true;
    try {
      const res = await shopuserInfo({});
      const { data } = res.result;
      // console.log('用户详情: ', data);
      userInfo.setUserInfo(data);
    } catch {
      /** empty */
    } finally {
      userLoading.value = false;
    }
  };
  getUserInfo();

  mitt.on('getUserInfo', getUserInfo);
  onBeforeUnmount(() => {
    mitt.off('getUserInfo', getUserInfo);
  });
}
